package com.example.courseapp.data

import android.R
import android.content.Context
import android.content.Intent
import android.content.SharedPreferences
import android.text.TextUtils
import android.util.Log
import com.example.courseapp.MainActivity
import com.example.courseapp.data.model.LoggedInUser
import com.example.courseapp.data.model.UserInfo

/**
 * Class that requests authentication and user information from the remote data source and
 * maintains an in-memory cache of login status and user credentials information.
 */

class LoginRepository(val dataSource: LoginDataSource) {

    // in-memory cache of the loggedInUser object
    var user: LoggedInUser? = null
        private set

    val isLoggedIn: Boolean
        get() = user != null

    /**
     * 初始化数据
     */
    init {
        // If user credentials will be cached in local storage, it is recommended it be encrypted
        // @see https://developer.android.com/training/articles/keystore
        // 初始化数据
        dataSource.initData()
        Log.d("dataSource.userMap内容",dataSource.userMap.toString())
        user = null

    }

    /**
     * 注销登陆
     */
    fun logout(context:Context) {
        user = null
        // 清除缓存信息
        dataSource.logout(context)
    }

    /**
     * 登陆并初始化数据
     */
    fun login(context: Context, username: String, password: String): Result<LoggedInUser> {
        // handle login
        val result = dataSource.login(context,username, password)
        Log.d("data reLog username",username)
        // Log.d("data reLog context",context.toString())

        if (result is Result.Success) {
            setLoggedInUser(result.data)
        }

        return result
    }

    private fun setLoggedInUser(loggedInUser: LoggedInUser) {
        this.user = loggedInUser
        // If user credentials will be cached in local storage, it is recommended it be encrypted
        // @see https://developer.android.com/training/articles/keystore
    }
}